﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler
{
    public class ProductDelCommandHandler : IRequestHandler<ProductDelCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IRepository<Product> proRep;
        public ProductDelCommandHandler(IMapper mapper, IRepository<Product> proRep)
        {
            this.mapper = mapper;
            this.proRep = proRep;
        }

        public  async Task<APIResult<object>> Handle(ProductDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = Codes.删除成功;
            result.Message = Codes.删除成功.ToString();

            try
            {
                var entity = mapper.Map<Product>(request);
                entity.IsDeleted = true;
                entity.DeletedTime = DateTime.Now;
                await proRep.UpdateAsync(entity);
            }
            catch (Exception ex)
            {
                result.Code = Codes.删除失败;
                result.Message = Codes.删除失败.ToString() + "，" + ex.Message;
            }

            return await Task.FromResult(result);
        }
    }
}
